<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="程序号">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                            v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                        </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.dropDownData" @press-enter="huiche" />
            </a-form-item>
            <!-- <CorporateSectorCascader
              :configCascader="configCascader"
              @changeCascader="changeCascader"
            /> -->
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar style="float: right" :items="['查询', '新增', '删除', '导出']" @add="addHandler" @del="deleteHandler"
            @select="selectHandler" @export="exports" @import="importHandler" @excel="downloadHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressDragLeaveHidesColumns="true"
          :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%"
          :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc"
          :localeText="localeText1" @columnResized="onColumnResized" @columnMoved="onColumnMoved"></AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys :page-size-options="pagingList1" :page-size="pagination.pageSize" :current="pagination.page"
      :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
      style="justify-content: center" />
    <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" :mask-closable="false" :width="400"
      popup-container=".arco-tabs-content" height="100%" :visible="pageData.showAdd" :ok-loading="pageData.pageLoading"
      placement="bottom" unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div style="min-width:1500px; overflow:auto;" class="scrollbar">
        <a-tabs   :lazy-load="true">
          <a-form ref="formRef" layout="horizontal" :model="dataForm" :label-col-props="{ span: 10 }"
            :wrapper-col-props="{ span: 14 }">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="程序号" field="programNumber"
                  :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '程序号必填' }]">
                  <a-input class="bacClass" v-model="dataForm.programNumber" @blur="inputBlur" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="程序名称" field="programName"
                  :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '程序名称必填' }]">
                  <a-input class="bacClass" v-model="dataForm.programName" @blur="inputBlur" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="程序类型" field="programType"
                  :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '程序类型必填' }]">
                  <a-select popup-container="html"  class="bacClass" v-model="dataForm.programType" @focus="focusSel1" @search="handleSearch1"
                    :loading1="loading1" allow-clear>
                    <a-option v-for="item in pageData.TypeNameList" :value="item">
                      {{ item }}
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="时间" field="times" :validate-trigger="['change', 'blur']"
                  :rules="[
                    { type: 'number', message: '输入不合法' },
                    { required: true, message: '时间必填' },
                  ]">
                  <a-input-number class="bacClass" v-model="dataForm.times" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="扣水缸数" field="retainingWater"
                  :validate-trigger="['change', 'blur']" :rules="[
                    { type: 'number', message: '输入不合法' },
                    { required: true, message: '扣水缸数必填' },
                  ]">
                  <a-input-number class="bacClass" v-model="dataForm.retainingWater" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="温差°C" field="temperature"
                  :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '温差°C必填' }]">
                  <a-input-number class="input-demo bacClass" :precision="1" v-model="dataForm.temperature" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="分类" field="classify" :validate-trigger="['change', 'blur']"
                  :rules="[{ required: true, message: '分类必填' }]">
                  <a-input class="bacClass" v-model="dataForm.classify" @blur="inputBlur" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="用水缸数" field="water" :validate-trigger="['change', 'blur']"
                  :rules="[
                    { type: 'number', message: '输入不合法' },
                    { required: true, message: '用水缸数必填' },
                  ]">
                  <a-input-number class="bacClass" v-model="dataForm.water" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="实际工艺时间" field="processTime"
                  :validate-trigger="['change', 'blur']" :rules="[
                    { type: 'number', message: '输入不合法' },
                    { required: true, message: '实际工艺时间(Min)必填' },
                  ]">
                  <a-input-number class="bacClass" v-model="dataForm.processTime" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="先加盐后加盐">
                  <a-select popup-container="html"  class="bacClass" v-model="dataForm.salt" placeholder=" ">
                    <a-option :value="0">先</a-option>
                    <a-option :value="1">后</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="冲水量(L)">
                  <a-input-number class="input-demo bacClass" :precision="1" v-model="dataForm.yieldWater" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="开头工艺">
                  <a-input class="bacClass" v-model="dataForm.begins" @blur="inputBlur" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label-col-flex="110px" label="备注">
                  <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear show-word-limit />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <div style="display: block" v-if="pageData.isShow">
                  <a-form-item label-col-flex="110px" field="picture">
                    <a-upload list-type="picture-card" action="/" image-preview :limit="1"
                      :customRequest="customUpload1" />
                  </a-form-item>
                </div>
                <div>
                  <a-form-item label-col-flex="110px" field="picture" v-if="!pageData.isShow">
                    <a-button type="primary" @click="picClick()">上传图片</a-button>
                  </a-form-item>
                </div>
              </a-col>
            </a-row>
            <div v-if="!pageData.isShow" style="border: 1px solid #b6b3b3;width: 813px; height: 413px;">
              <img list-type="picture-card"
                style="width: 800px; height: 400px;padding:2px;margin-top: 5px;margin-left: 5px;" :src="picUrl" />
            </div>
          </a-form>
        </a-tabs>
      </div>
      <template #footer>
        <a-button @click="pageData.showAdd = false">关闭</a-button>
        <a-button type="primary" @click="sideOk">保存</a-button>
        <a-button type="primary" @click="copyPro">复制</a-button>
      </template>
    </a-drawer>
    <a-modal v-model:visible="pageData.visible" title="选择程序号复制" :draggable="true">
      <a-form-item label="程序号" style="padding-left:17%">
        <a-select popup-container="html"  class="bacClass" style="width:250px" v-model="dataForm.programId" @focus="focusSel2"
          @search="handleSearch2" @change="copyCode" :loading7="loading2" :filter-option="false" allow-search>
          <a-option v-for="item in pageData.cxIdList" :value="item.programName" :key="item.id">
            {{ item.programName }}
          </a-option>
        </a-select>
      </a-form-item>
      <template #footer>
        <a-button size="small" @click="pageData.visible = false">取消</a-button>
        <a-button type="primary" size="small" @click="handleSave">确认</a-button>
      </template>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import { pagingList } from '@/api/paging'
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { AnyARecord } from 'dns'

import { localeText } from '@/api/aggridZw'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import { countBy } from 'lodash'

interface BrandInfo {
  id: any
  remark: any
  createName: string | undefined
  createTime: string | undefined
  updateName: string | undefined
  updateTime: string | undefined
  deleteState: any
  obsoleteState: any
  serial: any
  programType: any
  daysProofing: any
  programNumber: any
  times: any
  programName: any
  retainingWater: any
  water: any
  yieldWater: any
  temperature: any
  classify: any
  processTime: any
  salt: number
  begins: any
  file: string
  picture: string
  programId: any
}
export default {
  name: 'ProgramNumber',
  setup() {
    const total = ref(10)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      pagination.page = val
      doRefresh()
    }

    function change1(val: any) {
      pagination.pageSize = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)
    //查询方法
    function doRefresh() {
      pageData.pageLoading = true
      // updateGridState01()
      post({
        url: '/pdm/ProgramNumber/selectPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          deleteState: '0',
          programNumber: pageData.dropDownData,
        },
      })
        .then(({ data, code, message }: any) => {
          if (code === 200) {
            table.handleSuccess(data.list)
            gridOption.value.setRowData(data.list)
            total.value = data.total
          } else {
            Message.error(message)
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '程序号',
        key: 'programNumber',
        dataIndex: 'programNumber',
        width: 150,
      },
      {
        title: '程序名称',
        key: 'programName',
        dataIndex: 'programName',
        width: 150,
      },
      {
        title: '程序类型',
        key: 'programType',
        dataIndex: 'programType',
        width: 150,
      },
      {
        title: '时间',
        key: 'times',
        dataIndex: 'times',
        width: 150,
      },
      {
        title: '扣水缸数',
        key: 'retainingWater',
        dataIndex: 'retainingWater',
        width: 150,
      },
      {
        title: '温差°C',
        key: 'temperature',
        dataIndex: 'temperature',
        width: 150,
      },
      {
        title: '分类',
        key: 'classify',
        dataIndex: 'classify',
        width: 150,
      },
      {
        title: '用水缸数',
        key: 'water',
        dataIndex: 'water',
        width: 150,
      },
      {
        title: '实际工艺时间(Min)',
        key: 'processTime',
        dataIndex: 'processTime',
        width: 150,
      },
      {
        title: '先加盐后加盐',
        key: 'salt',
        dataIndex: 'salt',
        slotName: 'salt',
        width: 150,
      },
      {
        title: '冲水量(L)',
        key: 'yieldWater',
        dataIndex: 'yieldWater',
        width: 150,
      },
      {
        title: '开头工艺',
        key: 'begins',
        dataIndex: 'begins',
        width: 150,
      },
      {
        title: '图片',
        key: 'picture',
        dataIndex: 'picture',
        slotName: 'picture',
        width: 150,
        fixed: 'right',
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },
      // {
      //     title: "创建人",
      //     key: "createName",
      //     dataIndex: "createName",
      //     width: 150
      // },
      // {
      //     title: "创建时间",
      //     key: "createTime",
      //     dataIndex: "createTime",
      //     width: 200
      // },
      // {
      //     title: "最后修改人",
      //     key: "updateName",
      //     dataIndex: "updateName",
      //     width: 150
      // },
      // {
      //     title: "最后修改时间",
      //     key: "updateTime",
      //     dataIndex: "updateTime",
      //     width: 200
      // },
      {
        title: '操作',
        key: 'act',
        slotName: 'act',
        width: 150,
        fixed: 'right',
      },
    ])
    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
      }
      //
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 80
        obj['cellRenderer'] = {
          template: `<el-button style="color:#165dff;" link @click="a">修改</el-button>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              a,
            }
          },
        }
      }
      if (o.slotName === 'salt') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['cellRenderer'] = {
          template: `<div>{{val}}</div>`,
          setup(props: any) {
            let val = ref()
            val.value = props.params.data.salt == 0 ? '先' : '后'
            return {
              val,
            }
          },
        }
      }
      if (o.slotName === 'picture') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['width'] = 110
        obj['lockPosition'] = 'right'
        obj['cellRenderer'] = {
          template: `
          <a-space>
                <span v-if="val == ''">暂无图片</span>    
                <a-image v-else :src="p" style="width: 50px;height: 20px;" />
            </a-space>`,
          setup(props: any) {
            let p = ref()
            let val = props.params.data.picture
            p.value = baseURL + props.params.data.picture
            return {
              p,
              val,
            }
          },
        }
      }
      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)

    const pageData = reactive({
      nameList: [],
      showAdd: false,
      sideTitle: '新增程序号',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      TypeNameList: [],
      file: '',
      isShow: false,
      isShow2: false,
      visible: false,
      cxIdList: [],
    })
    // let configCascader = ref<{}>({
    //   corporateWidth: '200px', //公司宽度
    //   sectorWidth: '200px', //部门宽度
    //   corporateRquired: false, //公司是否必填
    //   sectorRquired: false, //部门是否必填
    //   size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    //   corporateName: '采购公司', //公司label
    //   sectorName: '采购部门', //部门label
    // })
    // const changeCascader = (data: {}) => {
    //   console.log(data)
    // }
    interface gcType {
      id: any
      company: any
    }
    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({ programNumber: '', deleteState: 0 })
    }

    //下拉数据
    const options = ref<any>(pageData.nameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = { programNumber: value, deleteState: 0 }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.nameList
        loading.value = false
      } else {
        options.value = []
      }
    }
    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: '/pdm/ProgramNumber/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          let dataList: any = []
          data.forEach(function (o: any) {
            dataList.push(o['programNumber'])
          })
          pageData.nameList = dataList
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      // 切换tap到本页面执行的方法
      emitter.on('ProgramNumber', () => {
        doRefresh()
      })
      pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
      //弹出层的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight
      }
      window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight
        }
      })
    })

    let cxbl = {}
    //查询
    const selectHandler = () => {
      pagination.page = 1
      cxbl = pageData.dropDownData
      doRefresh()
    }
    const queryData = reactive({
      programType: '',
    })
    // let pic2 = document.getElementById("pic2")
    const addHandler = () => {
      pageData.isShow = true
      // pageData.isShow2 = true
      for (var key in dataForm) {

        if (key === 'id') {
          dataForm[key] = null
        } else {
          dataForm[key] = ''
        }
      }

      // const pic2 = document.createElement("pic2");
      // pic2.style.display = "block";

      pageData.showAdd = true
      pageData.sideTitle = '新增程序号'
    }
    const dataForm = reactive<BrandInfo>({
      id: null,
      remark: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      deleteState: 0,
      obsoleteState: '',
      serial: '',
      programType: '',
      daysProofing: '',
      programNumber: '',
      times: '',
      programName: '',
      retainingWater: '',
      water: '',
      yieldWater: 0,
      temperature: 0,
      classify: '',
      processTime: '',
      salt: 0,
      begins: '',
      file: '',
      picture: '',
      programId: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          formRef.value?.validate().then((err) => {
            if (!err) {
              if (pageData.sideTitle === '新增程序号') {
                pageData.pageLoading = true
                if (pageData.file != '') {
                  let fd = new FormData()
                  fd.append('file', pageData.file)
                  axios
                    .post(baseURL + '/minio/file/upload', fd, {
                      headers: {
                        'Content-Type': 'multipart/form-data',
                        token: sessionStorage.getItem('USER-TOKEN-KEY'),
                      },
                    })
                    .then((res: any) => {
                      if (res.data.code === 200) {
                        dataForm.picture = res['data']['data']['data']
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                      post({
                        url: '/pdm/ProgramNumber/insert',
                        data: [dataForm],
                      })
                        .then((res: any) => {
                          if (res.code === 200) {
                            formRef.value?.resetFields()
                            pageData.showAdd = false
                            Message.success({
                              content: '新增成功',
                              duration: 5000,
                            })
                          } else {
                            Message.error({
                              content: res.message,
                              duration: 5000,
                            })
                          }
                          //doRefresh();
                        })
                        .finally(() => {
                          doRefresh()
                          pageData.pageLoading = false
                        })
                    })
                } else {
                  post({
                    url: '/pdm/ProgramNumber/insert',
                    data: [dataForm],
                  })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false
                        Message.success({
                          content: '新增成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                      //doRefresh();
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
                }
              } else if (pageData.sideTitle === '修改程序号') {
                pageData.pageLoading = true
                if (pageData.file != '') {
                  let fd = new FormData()
                  fd.append('file', pageData.file)
                  axios
                    .post(baseURL + '/minio/file/upload', fd, {
                      headers: {
                        'Content-Type': 'multipart/form-data',
                        token: sessionStorage.getItem('USER-TOKEN-KEY'),
                      },
                    })
                    .then((res: any) => {
                      if (res.data.code === 200) {
                        dataForm.picture = res['data']['data']['data']
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                      post({
                        url: '/pdm/ProgramNumber/update',
                        data: [dataForm],
                      })
                        .then((res: any) => {
                          if (res.code === 200) {
                            formRef.value?.resetFields()
                            pageData.showAdd = false
                            Message.success({
                              content: '修改成功',
                              duration: 5000,
                            })
                          } else {
                            Message.error({
                              content: res.message,
                              duration: 5000,
                            })
                          }
                          //doRefresh();
                        })
                        .finally(() => {
                          doRefresh()
                          pageData.pageLoading = false
                        })
                    })
                } else {
                  post({
                    url: '/pdm/ProgramNumber/update',
                    data: [dataForm],
                  })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false
                        Message.success({
                          content: '修改成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                      //doRefresh();
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
                }
              }
            }
          })
        }
      })
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true
          post({
            url: '/pdm/ProgramNumber/delete',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 6000,
                })
                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '删除失败',
                  duration: 6000,
                })
              }
            })
            .finally(() => {
              pageData.pageLoading = false
            })
        },
      })
    }
    let picUrl = ref()
    let picData = ''
    const editHandler = (record: BrandInfo) => {
      picData = record.picture
      // pic1.value.style.display = "none";
      // pic2.value.style.display = "block";
      // pic2.value.show()
      //循环对象 赋值
      for (let key in record) {
        dataForm[key] = record[key]
      }
      if (record.picture == null || record.picture == '') {
        pageData.isShow = true
      } else {
        pageData.isShow = false
        picUrl.value = baseURL + record.picture
        console.log(picUrl.value);

      }
      pageData.isShow2 = true
      dataForm.salt = record.salt
      pageData.sideTitle = '修改程序号'
      pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值只能是英文数字组合或英文，数字！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    const inputBlur = () => {
      dataForm.programNumber = dataForm.programNumber.toUpperCase()
      dataForm.programName = dataForm.programName.toUpperCase()
      dataForm.classify = dataForm.classify.toUpperCase()
      dataForm.begins = dataForm.begins.toUpperCase()
      dataForm.remark = dataForm.remark.toUpperCase()
    }
    //导出
    const exports = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        let idList: any = []
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          idList.push(o['id'])
        })
        //将表头拼接出来
        let head =
          '<th>程序号</th><th>程序名称</th><th>程序类型</th><th>时间</th><th>扣水缸数</th><th>温差°C</th><th>分类</th><th>用水缸数</th><th>实际工艺时间(Min)</th><th>先加盐后加盐</th><th>冲水量(L)</th><th>开头工艺</th><th>备注</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return (
            gridOption.value
              .getSelectedRows()
              .map((o: any) => {
                return o.id
              })
              .indexOf(o['id']) !== -1
          )
        })
        let body = ''
        nowRow.forEach(function (o) {
          body += '<tr><td>' + o['programNumber'] + '</td>'
          body += '<td>' + o['programName'] + '</td>'
          body += '<td>' + o['programType'] + '</td>'
          body += '<td>' + o['times'] + '</td>'
          body += '<td>' + o['retainingWater'] + '</td>'
          body += '<td>' + o['temperature'] + '</td>'
          body += '<td>' + o['classify'] + '</td>'
          body += '<td>' + o['water'] + '</td>'
          body += '<td>' + o['processTime'] + '</td>'
          body += '<td>' + (o['salt'] === 0 ? '先' : '后') + '</td>'
          body += '<td>' + o['yieldWater'] + '</td>'
          body += '<td>' + o['begins'] + '</td>'
          body += '<td>' + o['remark'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '程序号定义', body)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`
      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      axios
        .get(baseURL + '/pdm/ProgramNumber/uploadModel', {
          responseType: 'blob',
          headers: {
            token: sessionStorage.getItem('USER-TOKEN-KEY'),
          },
        })
        .then((res) => {
          if (res.status === 200) {
            filedownload(res.data, '程序号定义.xlsx')
          }
        })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
          .post(baseURL + '/pdm/ProgramNumber/importModelData', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((result) => {
            if (result.data['code'] === 200) {
              Message.success('导入成功')
            } else {
              Message.error(result.data.message)
            }
          })
          .finally(() => {
            pageData.pageLoading = false
            doRefresh()
          })
      })
      inputEle.click()
    }
    //程序类型 下拉框得到焦点
    const focusSel1 = () => {
      selCxAll1({ programType: '', deleteState: 0 })
    }

    //下拉数据
    const options1 = ref<any>(pageData.TypeNameList)
    const loading1 = ref(false)
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = { programType: value, deleteState: 0 }
        loading.value = true
        selCxAll1(ob)
        options.value = pageData.TypeNameList
        loading.value = false
      } else {
        options.value = []
      }
    }
    //下拉框查询
    function selCxAll1(val: any) {
      post({
        url: '/pdm/ProgramType/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          let dataList: any = []
          data.forEach(function (o: any) {
            dataList.push(o['programType'])
          })
          pageData.TypeNameList = dataList
        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      })
    }

    //下拉框得到焦点 程序号
    const focusSel2 = () => {
      selCxAll2({ "programNumber": "", deleteState: 0 });
    }

    //下拉数据 程序号
    const options2 = ref<any>(pageData.cxIdList);
    const loading2 = ref(false);
    const handleSearch2 = (value: any) => {
      if (value) {
        const ob = { programNumber: value, deleteState: 0 }
        loading2.value = true;
        selCxAll2(ob);
        options2.value = pageData.cxIdList;
        loading2.value = false;
      } else {
        options2.value = []
      }
    };
    //下拉框查询 程序号
    function selCxAll2(val: any) {
      post({
        url: "/pdm/ProgramNumber/getProgramNumber",
        data: val
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.cxIdList = data.list;
        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      });
    }
    // //设置权限
    // // ['查询', '新增', '删除', '导出', '导入']
    // const permissionStore = usePermission()

    // if (permissionStore.hasPermisson('ppzl.cx')) {

    //     pageData.btnList.push("查询")
    // }
    // if (permissionStore.hasPermisson('ppzl.xz')) {
    //     pageData.btnList.push("新增")
    // }
    // if (permissionStore.hasPermisson('ppzl.sc')) {
    //     pageData.btnList.push("删除")
    // }
    // if (permissionStore.hasPermisson('ppzl.dc')) {
    //     pageData.btnList.push("导出")
    // }
    // if (permissionStore.hasPermisson('ppzl.dr')) {
    //     pageData.btnList.push("导入")
    // }
    // if (permissionStore.hasPermisson('ppzl.xg')) {
    //     pageData.isEdit = true
    // }
    // console.log(permissionStore.hasPermisson('ppzl.cx'));
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
    }
    //文件上传
    function customUpload1(info: any) {
      info.onSuccess('')
      pageData.file = info.fileItem.file
      return info
    }

    const picClick = () => {
      pageData.isShow = true
      picData = ''
      picUrl.value = ''
      dataForm.picture = ''
    }

    //复制
    let program = ''
    function copyPro() {
      pageData.visible = true
      dataForm.programId = ''
    }

    function handleSave() {
      let ids:any = pageData.cxIdList.find((o:any) => o.programName === program)
      post({
        url: "/pdm/ProgramNumber/PdmProgramNumberId",
        data: {
          id: ids.id
        }
      }).then(({ data, code, message }: any) => {
        if (code === 200) {
          for (let key in dataForm) {
            if (key !== 'id' && key !== 'programId' && key !== 'programNumber') {
              dataForm[key] = data[key];
            }
          }
          if (data.picture != '') {
            picUrl.value = baseURL + '/minio/file/download/zzy/' + data.picture
            pageData.isShow = false
          } else {
            pageData.isShow = true
            data.picture = ''
            dataForm.picture = ''
          }
          pageData.visible = false
        } else {
          Message.error({
            content: message,
            duration: 5000,
          });
        }
      });
    }

    const copyCode = () => {
      program = dataForm.programId
      dataForm.programId = dataForm.programId.split('——')[0]
    }

    const localeText1: any = ref(localeText)
    const huiche = () => {
      doRefresh()
    }
    const pagingList1: any = ref(pagingList)
    const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('ProgramNumber01', gridOption, colState, tc)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized = () => {
      saveGridState01()
    }
    return {
      copyCode,
      handleSave,
      copyPro,
      saveOrUpdateGridState01,
      saveGridState01,
      updateGridState01,
      onColumnMoved,
      onColumnResized,
      colState,
      pagingList1,
      huiche,
      localeText1,
      picUrl,
      picClick,
      customUpload1,
      editHandler,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      // configCascader,
      // changeCascader,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      isChiese,
      inputBlur,
      exports,
      options,
      options1,
      options2,
      loading,
      loading1,
      loading2,
      handleSearch,
      handleSearch1,
      handleSearch2,
      focusSel,
      focusSel1,
      focusSel2,
      downloadHandler,
      importHandler,
      headerShow,
      handleChange,
      PageSize,
      change1,
      defaultColDef,
      tc,
      gridOption,
      gridReady,
      total,
      page,
      size,
    }
  },
  components: { Toolbar, PageTabelLayout,  },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-image arco-image-with-footer-inner) {
  width: 400px;
  height: 500px
}
</style>